package com.settlement.system.common.util;


import java.util.Base64;

/**
 * 简单的加密类
 */
public class SimpleEncryptHelper {
    private static final byte[] EN_KEY_STORE = {
            0x03, 0x07, 0x0f, 0x00,
            0x0a, 0x01, 0x0b, 0x02,
            0x0e, 0x0c, 0x05, 0x08,
            0x0d, 0x06, 0x09, 0x04
    };
    private static final byte[] DE_KEY_STORE = {
            0x03, 0x05, 0x07, 0x00,
            0x0f, 0x0a, 0x0d, 0x01,
            0x0b, 0x0e, 0x04, 0x06,
            0x09, 0x0c, 0x08, 0x02
    };


    /**
     * 加密
     * @param data byte[]
     * @return byte[]
     */
    public static byte[] encode(byte[] data) {
        byte[] result = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            result[i] += (EN_KEY_STORE[(data[i] >>> 4) & 0x0F] << 4);
            result[i] += (EN_KEY_STORE[data[i] & 0x0F]);
        }
        return result;
    }

    /**
     * 解密
     * @param data byte[]
     * @return byte[]
     */
    public static byte[] decode(byte[] data) {
        byte[] result = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            result[i] += (DE_KEY_STORE[(data[i] >>> 4) & 0x0F] << 4);
            result[i] += (DE_KEY_STORE[data[i] & 0x0F]);
        }
        return result;
    }

    public static String encode(String str){
        byte[] bytes = str.getBytes();
        byte[] encode = SimpleEncryptHelper.encode(bytes);
        return Base64.getEncoder().encodeToString(encode);
    }

    public static String decode(String str){
        byte[] decode = Base64.getDecoder().decode(str);
        byte[] decodeArray = SimpleEncryptHelper.decode(decode);
        return new String(decodeArray);
    }


    public static void main(String[] args) {
        String str = "test";
        String encode = encode(str);
        System.out.println(encode);
        System.out.println(decode(encode));
    }
}


